<template>
  <BaseDialog
    :visible="dialogVisible"
    title='重置密码'
    width="500px"
    @update:visible="handleUpdateVisible"
    @confirm="handleConfirm"
    @cancel="handleCancel"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="原密码" prop="oldPassword" v-if="false">
        <el-input
          v-model="formData.oldPassword"
          type="password"
          placeholder="请输入原密码"
          show-password
          clearable
        />
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="formData.newPassword"
          type="password"
          placeholder="请输入新密码"
          show-password
          clearable
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="formData.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
          clearable
        />
      </el-form-item>
    </el-form>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import BaseDialog from '@/components/BaseDialog.vue'
import { encryptPassword } from '@/utils/crypto'
import { resetUserPasswordWithOldPassword } from '@/api/user'
import type { User } from '@/types'

// Props
interface Props {
  visible: boolean
  userData?: User | null
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  userData: null
})

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const formRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (value !== formData.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 监听visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    initForm()
  }
})

// 监听dialogVisible变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 初始化表单
const initForm = () => {
  // 重置表单数据
  formData.oldPassword = ''
  formData.newPassword = ''
  formData.confirmPassword = ''
  
  // 清除验证
  formRef.value?.clearValidate()
}

// 确认操作
const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    // 验证表单
    await formRef.value.validate()
    
    // // 验证原密码
    // const encryptedOldPassword = encryptPassword(formData.oldPassword)
    // if (encryptedOldPassword !== props.userData?.password) {
    //   ElMessage.error('原密码错误')
    //   return
    // }
    
    // 准备提交数据 - 传递完整的User对象，只更新password字段
    const submitData: User = {
      id: props.userData?.id || 0,
      name: null,
      username: null,
      eMail: null,
      roleId: null,
      role: null,
      password: encryptPassword(formData.newPassword) // 新密码加密
    }
    
    // 调用重置密码的API
    await resetUserPasswordWithOldPassword(submitData)
    
    ElMessage.success('密码重置成功')
    emit('success')
    dialogVisible.value = false
  } catch (error) {
    console.error('重置密码失败:', error)
    ElMessage.error('重置密码失败')
  }
}

// 更新可见性
const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.el-form {
  padding: 20px 0;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
